package com.tarena.lbs.activity.controller;

import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.param.ActivityStatusUpdateParam;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.api.pojo.dto.StoreDTO;
import com.tarena.lbs.user.api.pojo.dto.UserDTO;
import com.tarena.lbs.user.api.pojo.dto.UserGroupDTO;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;

/**
 * 活动相关功能接口
 */
@Slf4j
@RestController
@Tag(name = "活动服务", description = "活动服务")
@RequestMapping("/admin/marketing/marketingActivity/info")
public class ActivityController {

    @Autowired
    private ActivityService activityService;

    @Operation(summary = "商家活动列表")
    @PostMapping("/list")
    public ResponseEntity<Result<PageResult<ActivityVO>>> pageList(@RequestBody ActivityQuery query) {
        try {
            log.info("查询商家活动列表，参数: {}", query);
            PageResult<ActivityVO> result = activityService.pageList(query);
            return ResponseEntity.ok(new Result<>(result));
        } catch (BusinessException e) {
            log.error("业务异常: {}", e.getMessage());
            return ResponseEntity.ok(Result.fail(e.getMessage(), null));
        } catch (Exception e) {
            log.error("查询活动列表失败: {}", e.getMessage(), e);
            PageResult<ActivityVO> emptyResult = new PageResult<>();
            return ResponseEntity.ok(new Result<>("FAIL", "查询活动列表失败，请稍后重试", emptyResult));

        }
    }

    @Operation(summary = "商家活动保存")
    @PostMapping("/save")
    public ResponseEntity<Result<String>> activitySave(@Valid @RequestBody ActivityAddParam param) {
        try {
            log.info("保存商家活动，参数: {}", param);
            activityService.saveActivity(param);
            return ResponseEntity.ok(new Result<>("活动保存成功"));
        } catch (BusinessException e) {
            log.error("业务异常: {}", e.getMessage());
            return ResponseEntity.ok(Result.fail("-1", e.getMessage()));
        } catch (ParseException e) {
            log.error("日期格式错误: {}", e.getMessage());
            return ResponseEntity.ok(Result.fail("-1", "日期格式错误，请使用 yyyy-MM-dd HH:mm:ss 格式"));
        } catch (Exception e) {
            log.error("保存活动失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(Result.fail("-1", "保存活动失败，请稍后重试"));
        }
    }

    @Operation(summary = "商家活动详情")
    @GetMapping("/detail/{id}")
    public ResponseEntity<Result<ActivityVO>> activityDetail(@PathVariable("id") Integer id) {
        try {
            log.info("查询商家活动详情，ID: {}", id);
            ActivityVO activity = activityService.getActivityById(id);
            return ResponseEntity.ok(new Result<>(activity));
        } catch (BusinessException e) {
            log.error("业务异常: {}", e.getMessage());
            return ResponseEntity.ok(Result.fail(e.getMessage(), null));
        } catch (Exception e) {
            log.error("查询活动详情失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(Result.fail("查询活动详情失败，请稍后重试", null));

        }
    }



    @Operation(summary = "商家活动删除")
    @PostMapping("/delete/{id}")
    public ResponseEntity<Result<String>> activityDelete(@PathVariable("id") Integer id) {
        try {
            log.info("删除商家活动，ID: {}", id);
            activityService.deleteActivity(id);
            return ResponseEntity.ok(new Result<>("活动删除成功"));
        } catch (BusinessException e) {
            log.error("业务异常: {}", e.getMessage());
            return ResponseEntity.ok(new Result<>(e.getMessage()));
        } catch (Exception e) {
            log.error("删除活动失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(new Result<>("删除活动失败，请稍后重试"));
        }
    }

    @Operation(summary = "根据用户ID列表获取用户信息")
    @GetMapping("/users")
    public ResponseEntity<Result<List<UserDTO>>> getUsersByIds(@RequestParam String userIds) {
        try {
            log.info("根据用户ID列表查询用户信息，userIds: {}", userIds);
            List<UserDTO> result = activityService.getUsersByIds(userIds);
            return ResponseEntity.ok(new Result<>(result));
        } catch (Exception e) {
            log.error("查询用户信息失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(Result.fail("查询用户信息失败，请稍后重试", null));
        }
    }

    @Operation(summary = "获取用户分组信息")
    @GetMapping("/userGroup/{id}")
    public ResponseEntity<Result<UserGroupDTO>> getUserGroupById(@PathVariable("id") Integer id) {
        try {
            log.info("查询用户分组信息，ID: {}", id);
            UserGroupDTO result = activityService.getUserGroupById(id);
            return ResponseEntity.ok(new Result<>(result));
        } catch (Exception e) {
            log.error("查询用户分组信息失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(Result.fail("查询用户分组信息失败，请稍后重试", null));
        }
    }

    @Operation(summary = "更新活动状态")
    @PostMapping("/updateStatus")
    public ResponseEntity<Result<String>> updateActivityStatus(@RequestBody ActivityStatusUpdateParam param) {
        try {
            log.info("更新活动状态，ID: {}, 启用状态: {}", param.getId(), param.getEnableStatus());
            activityService.updateActivityStatus(param.getId(), param.getEnableStatus());
            return ResponseEntity.ok(new Result<>("活动状态更新成功"));
        } catch (Exception e) {
            log.error("更新活动状态失败: {}", e.getMessage(), e);
            return ResponseEntity.ok(new Result<>("更新活动状态失败，请稍后重试"));
        }
    }

    /**
     * 处理参数校验异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result<String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        log.error("参数校验失败: {}", ex.getMessage());
        // 获取第一个校验失败的字段错误信息
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(fieldError -> fieldError.getField() + ": " + fieldError.getDefaultMessage())
                .findFirst()
                .orElse("参数校验失败");
        return ResponseEntity.ok(new Result<>(errorMessage));
    }
}